package com.empire.devops.emops.generator;

import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.ITypeConvert;
import com.baomidou.mybatisplus.generator.config.converts.select.BranchBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import org.jetbrains.annotations.NotNull;

/**
 * 代码生成自定义数据类型，此处用的oracle数据库，
 * 若是mysql  MySqlTypeConvert重写目标方法即可
 */
public class MyTypeConvert implements ITypeConvert {
    public static final MyTypeConvert INSTANCE = new MyTypeConvert();

    public MyTypeConvert() {
    }

    @Override
    public IColumnType processTypeConvert(@NotNull GlobalConfig globalConfig, @NotNull TableField tableField) {
        return ITypeConvert.super.processTypeConvert(globalConfig, tableField);
    }


    @Override
    public IColumnType processTypeConvert(@NotNull GlobalConfig globalConfig, @NotNull String fieldType) {
        return (IColumnType) MyTypeConverts.use(fieldType).test(MyTypeConverts.containsAny(new CharSequence[]{"char", "clob"}).then(DbColumnType.STRING)).test(MyTypeConverts.containsAny(new CharSequence[]{"date", "timestamp"}).then((p) -> {
            return toDateType(globalConfig);
        })).test(MyTypeConverts.contains("number").then(MyTypeConvert::toNumberType)).test(MyTypeConverts.contains("float").then(DbColumnType.FLOAT)).test(MyTypeConverts.contains("blob").then(DbColumnType.BLOB)).test(MyTypeConverts.containsAny(new CharSequence[]{"binary", "raw"}).then(DbColumnType.BYTE_ARRAY)).or(DbColumnType.STRING);
    }

    private static IColumnType toNumberType(String typeName) {
        if (typeName.matches("number\\([0-9]\\)")) {
            return DbColumnType.INTEGER;
        } else {
            return DbColumnType.LONG;
        }
    }

    protected static IColumnType toDateType(GlobalConfig config) {
        switch (config.getDateType()) {
            case ONLY_DATE:
                return DbColumnType.DATE;
            case SQL_PACK:
                return DbColumnType.TIMESTAMP;
            case TIME_PACK:
                return DbColumnType.LOCAL_DATE_TIME;
            default:
                return DbColumnType.STRING;
        }
    }

    static BranchBuilder<String, IColumnType> containsAny(CharSequence... values) {
        return BranchBuilder.of((s) -> {
            CharSequence[] var2 = values;
            int var3 = values.length;

            for (int var4 = 0; var4 < var3; ++var4) {
                CharSequence value = var2[var4];
                if (s.contains(value)) {
                    return true;
                }
            }

            return false;
        });
    }
}